package com.conan.dailyflickr.provider;

import java.util.Map;

import android.content.Context;
import android.content.SharedPreferences;

public abstract class AbsPrefModel implements IModelSaveContract{

	private static String TAG = "AbsPrefModel";
	public int mId;
	
	public AbsPrefModel(int instanceId) {
		mId = instanceId;
	}
	
	// abstract methods	
	public abstract String getPrefName();
	public abstract void init();

	@Override
	public void setValueForPref(String key, String value) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Map<String, String> getPrefsToSave() {
		return null;
	}
	
	public void savePreferences (Context context){
		Map<String, String> keyValuePairs = getPrefsToSave();
		if(keyValuePairs == null){
			return;
		}
		//going to save some values
		SharedPreferences.Editor prefs = 
					context.getSharedPreferences(getPrefName(), 0).edit();
		
		for(String key:keyValuePairs.keySet()){
			String value = keyValuePairs.get(key);
			savePref(prefs, key, value);
		}
		
		// finnaly commit values
		prefs.commit();
	}
	
	private void savePref(SharedPreferences.Editor prefs, String key, String value){
		String newKey = getStoredKeyForFieldName(key);
		prefs.putString(newKey, value);
	}
	
	private void removePref(SharedPreferences.Editor prefs, String key){
		String newKey = getStoredKeyForFieldName(key);
		prefs.remove(newKey);
	}
	
	protected String getStoredKeyForFieldName(String fieldName){
		return fieldName + "_" + mId;
	}
	
	public static void clearAllPreferences(Context context, String prefname){
		SharedPreferences prefs = context.getSharedPreferences(prefname, 0);
		SharedPreferences.Editor prefEditor = prefs.edit();
		prefEditor.clear();
		prefEditor.commit();
	}
	
	public boolean retievePrefs(Context ctx){
		SharedPreferences prefs = ctx.getSharedPreferences(getPrefName(), 0);
		Map<String, ?> keyValuePairs = prefs.getAll();
		boolean prefFound = false;
		for(String key: keyValuePairs.keySet()){
			if(isItMyPref(key) == true){
				String value = (String)keyValuePairs.get(key);
				setValueForPref(key, value);
				prefFound = true;
			}
		}
		return prefFound;
	}
	
	public void removePrefs(Context context){
		Map<String, String> keyValuePairs = getPrefsToSave();
		
		if(keyValuePairs == null){
			return;
		}
		
		// going to save some values
		SharedPreferences.Editor prefs = context.getSharedPreferences(getPrefName(), 0).edit();
		
		for(String key:keyValuePairs.keySet()){
			removePref(prefs, key);
		}
		
		// finally commit the values
		prefs.commit();
	}
	
	private boolean isItMyPref(String keyname){
		if(keyname.indexOf("_" + mId) > 0){
			return true;
		}
		return false;
	}
}
